using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 工单暂停/恢复命令。
/// </summary>
public sealed record HoldOnWorkOrderCommand(long WoId) : IRequest<IResult<bool>>;

internal sealed class HoldOnWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<HoldOnWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(HoldOnWorkOrderCommand request, CancellationToken cancellationToken)
    {
        var workOrder = await repo.GetByIdAsync(request.WoId, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找到要更新的工单");
        }

        // 工单处于暂停状态，进行恢复
        if (workOrder.Status is WoStatusEnum.OnHold)
        {
            workOrder.Recover();
        }
        else
        {
            // 工单暂停
            if (workOrder.Status is not WoStatusEnum.Scheduled and not WoStatusEnum.InProgress)
            {
                return Result.Failure("工单不处于已排产或生产状态，不能暂停");
            }

            workOrder.HoldOn();
        }

        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.LastStatus,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
